import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { AppVersion} from '@ionic-native/app-version'
import { FileOpener } from "@ionic-native/file-opener";
import { FileTransfer,FileTransferObject} from '@ionic-native/file-transfer'
import { File } from "@ionic-native/file";
import { AlertController,Platform } from 'ionic-angular';

/*
  Generated class for the UploadServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class UploadServiceProvider {

  constructor(
    public http: Http,
    private appVersion:AppVersion,
    private fileOpener:FileOpener,
    private transfer:FileTransfer,
    private file:File,
    private alertCtrl:AlertController,
    private platform:Platform
  ) 
    {
    console.log('Hello UploadServiceProvider Provider');
  }

  //下载安装app
  downloadApp(apkurl) {
    let url="http://"+apkurl;
    if (this.isAndroid()) {
      let alert = this.alertCtrl.create({
        title:  '地址'+url+'下载进度：0%',
        enableBackdropDismiss: false,
        buttons: ['后台下载']
      });
      alert.present();

      const fileTransfer: FileTransferObject = this.transfer.create();
      const apk = this.file.externalRootDirectory + 'android.apk'; //apk保存的目录

     // source填写你apk下载的地址
     fileTransfer.download(url, apk).then(() => {  
      this.fileOpener.open(apk, 'application/vnd.android.package-archive').then(() =>{  
          console.log('File is opened')  
      }).catch(e => {  
          console.log('Error openening file', e)  
      });  
    }); 

      fileTransfer.onProgress((event: ProgressEvent) => {
        let num = Math.floor(event.loaded / event.total * 100);
        if (num === 100) {
          alert.dismiss();
        } else {
          let title = document.getElementsByClassName('alert-title')[0];
          title && (title.innerHTML ='下载进度：' + num + '%');
        }
      });
    }
  }
  
  /**
   * 是否android真机环境
   * @return {boolean}
   */
  isAndroid(): boolean {
    return this.isMobile() && this.platform.is('android');
  }

   /**
   * 是否真机环境
   * @return {boolean}
   */
  isMobile(): boolean {
    return this.platform.is('mobile') && !this.platform.is('mobileweb');
  }
}
